import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    userInfo: localStorage.getItem('userInfo') || 'null' || {
      id: null,
      avatar: ''
    }
  }),
  actions: {
    login(token, userData) {
      this.token = token
      this.userInfo = {
        id: userData.id,
        username: userData.username || '用户',
        avatar: userData.avatar || 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
      }
      
      localStorage.setItem('token', token)
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    logout() {
      this.token = null
      this.userInfo = {
        id: null,
        avatar: ''
      }
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  },
  getters: {
    isAuthenticated: (state) => !!state.token,
    currentUser: (state) => state.userInfo,
    userId: (state) => state.userInfo.id
  }
})